"use client"

import type React from "react"

import { useState, useEffect, useRef } from "react"
import { Search, X, GripVertical, CheckCircle2, Circle, History, Save, RotateCcw, Camera } from "lucide-react"
import { cn } from "@/lib/utils"
import LoadingScreen from "./loading-screen"
import HistoryTimeline from "./history-timeline"
import ExportCard from "./export-card"
import AIAssistantButton from "./ai-assistant-button"
import type { Todo, Language } from "@/types"
import { StorageService } from "@/services/storage"
import { HistoryService } from "@/services/history"
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  type DragEndEvent,
} from "@dnd-kit/core"
import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from "@dnd-kit/sortable"
import { useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import TaskDetailsCard from "./task-details-card"

const languages: Language[] = [
  {
    code: "zh",
    name: "中",
    translations: {
      title: "TODO",
      placeholder: "新增待办事项...",
      submit: "提交",
      todayMotto: "今日事今日毕，勿将今事待明日！🌸",
      addFirstTodo: "添加你的第一个待办事项！📝",
      allTodos: "全部",
      importData: "导入(txt/json)",
      about: "关于我",
      openStar: "开⭐",
      markAllDone: "全部标为完成",
      finishAll: "全部标为已完成",
      clearAll: "清除全部",
      exportData: "导出数据",
      all: "全部",
      history: "历史记录",
      searchPlaceholder: "搜索...",
      editTodo: "双击编辑",
      totalTasks: "总任务",
      completedTasks: "已完成",
      pendingTasks: "待完成",
      backup: "备份数据",
      restore: "恢复数据",
      exportImage: "导出图片",
      aiAssistant: "AI助手",
      clearCompleted: "清除已完成",
      noHistory: "暂无历史记录",
      tasksCreated: "创建任务",
      tasksCompleted: "完成任务",
      completionRate: "完成率",
    },
  },
  {
    code: "en",
    name: "En",
    translations: {
      title: "TODO",
      placeholder: "Add a to-do item...",
      submit: "Add",
      todayMotto: "Act Now, Simplify Life.🌸",
      addFirstTodo: "Add your first todo item! 📝",
      allTodos: "All",
      importData: "Import(txt/json)",
      about: "About",
      openStar: "OPEN⭐",
      markAllDone: "Mark All Done",
      finishAll: "Finish all",
      clearAll: "Clear All",
      exportData: "Export data",
      all: "All",
      history: "History",
      searchPlaceholder: "Search...",
      editTodo: "Double click to edit",
      totalTasks: "Total",
      completedTasks: "Completed",
      pendingTasks: "Pending",
      backup: "Backup Data",
      restore: "Restore Data",
      exportImage: "Export Image",
      aiAssistant: "AI Assistant",
      clearCompleted: "Clear Completed",
      noHistory: "No history yet",
      tasksCreated: "Tasks Created",
      tasksCompleted: "Tasks Completed",
      completionRate: "Completion Rate",
    },
  },
]

interface SortableTodoItemProps {
  todo: Todo
  isEditing: boolean
  editingText: string
  onToggle: () => void
  onDelete: () => void
  onStartEdit: () => void
  onEditChange: (text: string) => void
  onSaveEdit: () => void
  onCancelEdit: () => void
  editTodo: string
}

function SortableTodoItem({
  todo,
  isEditing,
  editingText,
  onToggle,
  onDelete,
  onStartEdit,
  onEditChange,
  onSaveEdit,
  onCancelEdit,
  editTodo,
}: SortableTodoItemProps) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: todo.id,
    disabled: isEditing,
  })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  }

  const editInputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    if (isEditing && editInputRef.current) {
      editInputRef.current.focus()
      editInputRef.current.select()
    }
  }, [isEditing])

  const handleEditKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      onSaveEdit()
    } else if (e.key === "Escape") {
      onCancelEdit()
    }
  }

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={cn(
        "flex items-center gap-3 p-3 bg-orange-50 border-2 border-gray-300 rounded-full transition-all duration-200",
        isDragging && "opacity-50 shadow-lg",
        todo.completed && "opacity-60",
      )}
    >
      {!isEditing && (
        <div {...attributes} {...listeners} className="flex-shrink-0 cursor-grab active:cursor-grabbing">
          <GripVertical className="w-4 h-4 text-gray-400" />
        </div>
      )}

      <button onClick={onToggle} className="flex-shrink-0">
        {todo.completed ? (
          <CheckCircle2 className="w-5 h-5 text-green-600" />
        ) : (
          <Circle className="w-5 h-5 text-gray-400" />
        )}
      </button>

      {isEditing ? (
        <input
          ref={editInputRef}
          value={editingText}
          onChange={(e) => onEditChange(e.target.value)}
          onKeyPress={handleEditKeyPress}
          onBlur={onSaveEdit}
          className="flex-1 bg-transparent border-none outline-none text-gray-700 select-text"
        />
      ) : (
        <span
          onDoubleClick={onStartEdit}
          className={cn("flex-1 text-gray-700 cursor-pointer", todo.completed && "line-through text-gray-500")}
          title={editTodo}
        >
          {todo.text}
        </span>
      )}

      <button onClick={onDelete} className="flex-shrink-0 p-1 rounded-full hover:bg-red-100 transition-colors">
        <X className="w-4 h-4 text-gray-600" />
      </button>
    </div>
  )
}

export default function TodoApp() {
  const [isLoading, setIsLoading] = useState(true)
  const [todos, setTodos] = useState<Todo[]>([])
  const [inputValue, setInputValue] = useState("")
  const [currentLang, setCurrentLang] = useState<Language>(languages[0])
  const [searchQuery, setSearchQuery] = useState("")
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editingText, setEditingText] = useState("")
  const [currentView, setCurrentView] = useState<"all" | "history">("all")
  const [history, setHistory] = useState<any[]>([])

  const exportCardRef = useRef<HTMLDivElement>(null)
  const storageService = StorageService.getInstance()
  const historyService = HistoryService.getInstance()

  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 8,
      },
    }),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    }),
  )

  // Load data on mount
  useEffect(() => {
    const savedTodos = storageService.loadTodos()
    const savedLang = storageService.loadLanguage()
    const savedHistory = historyService.getHistory()

    if (savedTodos.length > 0) {
      setTodos(savedTodos.sort((a, b) => a.order - b.order))
    } else {
      // Add default todos
      const defaultTodos = [
        {
          id: "default-1",
          text: "编写一个朋友实用于工程创建，采用Go语言",
          completed: false,
          createdAt: new Date(),
          order: 0,
        },
        {
          id: "default-2",
          text: "写一个TodoList网站",
          completed: false,
          createdAt: new Date(),
          order: 1,
        },
      ]
      setTodos(defaultTodos)
    }

    if (savedLang) {
      const lang = languages.find((l) => l.code === savedLang)
      if (lang) setCurrentLang(lang)
    }

    setHistory(savedHistory)
  }, [])

  // Save data and update history when todos change
  useEffect(() => {
    if (todos.length > 0) {
      storageService.saveTodos(todos)
      historyService.updateDailyHistory(todos)
      setHistory(historyService.getHistory())
    }
  }, [todos])

  // Save language preference
  useEffect(() => {
    storageService.saveLanguage(currentLang.code)
  }, [currentLang])

  const addTodo = () => {
    if (inputValue.trim()) {
      const maxOrder = Math.max(...todos.map((t) => t.order), -1)
      const newTodo: Todo = {
        id: Date.now().toString(),
        text: inputValue.trim(),
        completed: false,
        createdAt: new Date(),
        order: maxOrder + 1,
      }
      setTodos([...todos, newTodo])
      setInputValue("")
    }
  }

  const toggleTodo = (id: string) => {
    setTodos(
      todos.map((todo) =>
        todo.id === id
          ? {
              ...todo,
              completed: !todo.completed,
              completedAt: !todo.completed ? new Date() : undefined,
            }
          : todo,
      ),
    )
  }

  const deleteTodo = (id: string) => {
    setTodos(todos.filter((todo) => todo.id !== id))
  }

  const startEdit = (id: string, text: string) => {
    setEditingId(id)
    setEditingText(text)
  }

  const saveEdit = () => {
    if (editingId && editingText.trim()) {
      setTodos(todos.map((todo) => (todo.id === editingId ? { ...todo, text: editingText.trim() } : todo)))
    }
    setEditingId(null)
    setEditingText("")
  }

  const cancelEdit = () => {
    setEditingId(null)
    setEditingText("")
  }

  const markAllDone = () => {
    setTodos(
      todos.map((todo) => ({
        ...todo,
        completed: true,
        completedAt: new Date(),
      })),
    )
  }

  const clearAll = () => {
    setTodos([])
  }

  const clearCompleted = () => {
    setTodos(todos.filter((todo) => !todo.completed))
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      addTodo()
    }
  }

  const handleBackup = () => {
    try {
      const backupData = storageService.createBackup()
      const dataBlob = new Blob([backupData], { type: "application/json" })
      const url = URL.createObjectURL(dataBlob)
      const link = document.createElement("a")
      link.href = url
      link.download = `todo-backup-${new Date().toISOString().split("T")[0]}.json`
      link.click()
      URL.revokeObjectURL(url)
    } catch (error) {
      alert("备份失败")
    }
  }

  const handleRestore = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const content = e.target?.result as string
          storageService.restoreFromBackup(content)
          window.location.reload() // Reload to apply restored data
        } catch (error) {
          alert("恢复失败，请检查文件格式")
        }
      }
      reader.readAsText(file)
    }
    event.target.value = ""
  }

  const handleExportImage = async () => {
    if (!exportCardRef.current) return

    try {
      // Dynamically import html2canvas
      const html2canvas = (await import("html2canvas")).default

      const canvas = await html2canvas(exportCardRef.current, {
        backgroundColor: "#f0f4f8",
        scale: 2,
        useCORS: true,
      })

      const link = document.createElement("a")
      link.download = `todo-summary-${new Date().toISOString().split("T")[0]}.png`
      link.href = canvas.toDataURL()
      link.click()
    } catch (error) {
      console.error("Export failed:", error)
      alert("导出失败")
    }
  }

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event

    if (over && active.id !== over.id) {
      const oldIndex = todos.findIndex((todo) => todo.id === active.id)
      const newIndex = todos.findIndex((todo) => todo.id === over.id)

      const newTodos = arrayMove(todos, oldIndex, newIndex)
      const updatedTodos = newTodos.map((todo, index) => ({
        ...todo,
        order: index,
      }))

      setTodos(updatedTodos)
    }
  }

  // Filter and sort todos: pending first, then completed
  const filteredTodos = todos
    .filter((todo) => todo.text.toLowerCase().includes(searchQuery.toLowerCase()))
    .sort((a, b) => {
      if (a.completed !== b.completed) {
        return a.completed ? 1 : -1
      }
      return a.order - b.order
    })

  // Statistics
  const totalTasks = todos.length
  const completedTasks = todos.filter((todo) => todo.completed).length
  const pendingTasks = totalTasks - completedTasks

  const t = currentLang.translations

  if (isLoading) {
    return <LoadingScreen onLoadingComplete={() => setIsLoading(false)} />
  }

  return (
    <>
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-4 select-none">
        <div className="max-w-4xl mx-auto">
          {/* Header */}
          <header className="flex justify-between items-center mb-8">
            <div className="flex items-center gap-2">
              <div className="w-3 h-3 bg-orange-300 rounded-full"></div>
              <div className="w-3 h-3 bg-orange-300 rounded-full"></div>
            </div>

            <div className="flex items-center gap-4">
              <span className="text-gray-600">{t.about}</span>
              <div className="flex gap-2">
                {languages.map((lang) => (
                  <button
                    key={lang.code}
                    onClick={() => setCurrentLang(lang)}
                    className={cn(
                      "px-3 py-1 rounded text-sm transition-colors",
                      currentLang.code === lang.code ? "bg-blue-500 text-white" : "text-gray-600 hover:bg-gray-200",
                    )}
                  >
                    {lang.name}
                  </button>
                ))}
              </div>
            </div>
          </header>

          {/* Title */}
          <div className="text-center mb-8">
            <h1 className="text-6xl font-bold text-orange-400 mb-2 tracking-wider flex items-center justify-center gap-2">
              {t.title}
              <span className="text-purple-400">🔗</span>
            </h1>
          </div>

          <div className="flex flex-col lg:flex-row gap-6">
            {/* Main Content */}
            <div className="flex-1">
              {/* Add Todo Input */}
              <div className="flex mb-6">
                <input
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder={t.placeholder}
                  className="flex-1 h-12 text-lg px-4 border-2 border-gray-300 rounded-l-lg focus:outline-none focus:border-gray-500 bg-white"
                />
                <button
                  onClick={addTodo}
                  className="h-12 px-6 bg-gray-200 hover:bg-gray-300 text-gray-800 rounded-r-lg border-2 border-l-0 border-gray-300 transition-colors"
                >
                  {t.submit}
                </button>
              </div>

              {/* Todo List */}
              <div className="border-2 border-gray-300 rounded-lg overflow-hidden bg-white">
                {/* Tab Header */}
                <div className="flex">
                  <button
                    onClick={markAllDone}
                    className="bg-green-100 hover:bg-green-200 text-gray-800 px-6 py-3 border-r border-gray-300 transition-colors"
                  >
                    {t.markAllDone}
                  </button>
                  <div className="flex-1 bg-white border-b border-gray-300 px-6 py-3 text-gray-700 font-medium flex justify-between items-center">
                    <span>{t.todayMotto}</span>
                    {/* Statistics */}
                    <div className="flex gap-4 text-sm">
                      <span className="text-blue-600">
                        {t.totalTasks}: {totalTasks}
                      </span>
                      <span className="text-green-600">
                        {t.completedTasks}: {completedTasks}
                      </span>
                      <span className="text-orange-600">
                        {t.pendingTasks}: {pendingTasks}
                      </span>
                    </div>
                  </div>
                </div>

                {/* Scrollable Todo Container */}
                <div className="h-96 overflow-y-auto custom-scrollbar">
                  <div className="p-6">
                    <div className="space-y-4">
                      {filteredTodos.length === 0 ? (
                        <div className="text-center text-gray-500 py-8">{t.addFirstTodo}</div>
                      ) : (
                        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
                          <SortableContext
                            items={filteredTodos.map((todo) => todo.id)}
                            strategy={verticalListSortingStrategy}
                          >
                            {filteredTodos.map((todo) => (
                              <SortableTodoItem
                                key={todo.id}
                                todo={todo}
                                isEditing={editingId === todo.id}
                                editingText={editingText}
                                onToggle={() => toggleTodo(todo.id)}
                                onDelete={() => deleteTodo(todo.id)}
                                onStartEdit={() => startEdit(todo.id, todo.text)}
                                onEditChange={setEditingText}
                                onSaveEdit={saveEdit}
                                onCancelEdit={cancelEdit}
                                editTodo={t.editTodo}
                              />
                            ))}
                          </SortableContext>
                        </DndContext>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Sidebar */}
            <div className="w-full lg:w-48 space-y-3">
              {/* Search */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-3 h-3 text-gray-400" />
                <input
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder={t.searchPlaceholder}
                  className="w-full h-8 pl-8 pr-3 text-sm border border-gray-300 rounded focus:outline-none focus:border-gray-500 bg-white"
                />
              </div>

              {/* View Tabs */}
              <div className="flex bg-gray-100 rounded p-1">
                <button
                  onClick={() => setCurrentView("all")}
                  className={cn(
                    "flex-1 py-1 px-2 text-xs rounded transition-colors",
                    currentView === "all" ? "bg-white text-gray-800 shadow-sm" : "text-gray-600",
                  )}
                >
                  {t.all}
                </button>
                <button
                  onClick={() => setCurrentView("history")}
                  className={cn(
                    "flex-1 py-1 px-2 text-xs rounded transition-colors flex items-center justify-center gap-1",
                    currentView === "history" ? "bg-white text-gray-800 shadow-sm" : "text-gray-600",
                  )}
                >
                  <History className="w-3 h-3" />
                  {t.history}
                </button>
              </div>

              {/* Content based on current view */}
              {currentView === "all" ? (
                <div className="bg-purple-100 rounded-lg p-3 space-y-2">
                  <button
                    onClick={markAllDone}
                    className="w-full text-gray-800 rounded py-2 text-sm hover:bg-purple-200 transition-colors"
                  >
                    {t.finishAll}
                  </button>

                  <button
                    onClick={clearCompleted}
                    className="w-full text-gray-800 rounded py-2 text-sm hover:bg-purple-200 transition-colors"
                  >
                    {t.clearCompleted}
                  </button>

                  <button
                    onClick={clearAll}
                    className="w-full text-gray-800 rounded py-2 text-sm hover:bg-purple-200 transition-colors"
                  >
                    {t.clearAll}
                  </button>

                  <button
                    onClick={handleBackup}
                    className="w-full text-gray-800 rounded py-2 text-sm hover:bg-purple-200 transition-colors flex items-center justify-center gap-1"
                  >
                    <Save className="w-3 h-3" />
                    {t.backup}
                  </button>

                  <div className="relative">
                    <input
                      type="file"
                      accept=".json"
                      onChange={handleRestore}
                      className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                    />
                    <button className="w-full text-gray-800 rounded py-2 text-sm hover:bg-purple-200 transition-colors flex items-center justify-center gap-1">
                      <RotateCcw className="w-3 h-3" />
                      {t.restore}
                    </button>
                  </div>

                  <button
                    onClick={handleExportImage}
                    className="w-full text-gray-800 rounded py-2 text-sm hover:bg-purple-200 transition-colors flex items-center justify-center gap-1"
                  >
                    <Camera className="w-3 h-3" />
                    {t.exportImage}
                  </button>
                </div>
              ) : (
                <div className="space-y-3">
                  <div className="bg-blue-50 rounded-lg p-3">
                    <HistoryTimeline history={history} currentLang={currentLang} />
                  </div>
                  <TaskDetailsCard todos={todos} currentLang={currentLang} />
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Hidden Export Card */}
      <div className="fixed -top-[9999px] left-0">
        <ExportCard ref={exportCardRef} todos={todos} currentLang={currentLang} />
      </div>

      {/* AI Assistant Button */}
      <AIAssistantButton />

      <style jsx global>{`
        .custom-scrollbar {
          scrollbar-width: thin;
          scrollbar-color: #cbd5e0 #f7fafc;
        }

        .custom-scrollbar::-webkit-scrollbar {
          width: 6px;
        }

        .custom-scrollbar::-webkit-scrollbar-track {
          background: #f7fafc;
          border-radius: 3px;
        }

        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: #cbd5e0;
          border-radius: 3px;
        }

        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background: #a0aec0;
        }
      `}</style>
    </>
  )
}
